package co.th.bjc.md.helper;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import co.th.bjc.md.common.ConnectDB;
import co.th.bjc.md.model.Region;

public class RegionHelper {

	private static Logger _log = Logger.getLogger(RegionHelper.class);
	
	public List<Region> findAllRegion() throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		List<Region> listRegion = new ArrayList<Region>(0);
		ConnectDB connectDB = null;
		try{
			StringBuffer condition = new StringBuffer("SELECT * FROM region");
			
			_log.info("SQL : " + condition.toString());
			connectDB = new ConnectDB();
			conn = connectDB.getConnection();
			stmt = conn.prepareStatement(condition.toString());
			rs = stmt.executeQuery();
			while (rs.next()){
				listRegion.add(this.setRegion(rs));
			}
		}catch(Exception ex){
			_log.error("findAllRegion --> " + ex.toString());
			ex.printStackTrace();
		}finally{
			if (rs != null) rs.close();
			if (stmt != null) stmt.close();
			connectDB.close();
		}
		return listRegion;
	}
	
	public Region findRegionByRegionCode(BigDecimal regionCode) throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		Region region = null;
		ConnectDB connectDB = null;
		try{
			String sql = "SELECT * FROM region WHERE region_id = ?";
			_log.info("SQL : " + sql);
			
			connectDB = new ConnectDB();
			conn = connectDB.getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setBigDecimal(1, regionCode);
			
			rs = stmt.executeQuery();
			if (rs.next()){
				region = this.setRegion(rs);
			}
		}catch(Exception ex){
			_log.error("findRegionByRegionCode --> " + ex.toString());
			ex.printStackTrace();
		}finally{
			if (rs != null) rs.close();
			if (stmt != null) stmt.close();
			connectDB.close();
		}
		return region;
	}
	
	private Region setRegion(ResultSet rs) throws Exception{
		Region region = new Region();
		region.setRegionId(rs.getBigDecimal("region_id"));
		region.setRegionNameTH(rs.getString("region_name_th"));
		region.setRegionNameEN(rs.getString("region_name_en"));
		return region;
	}
}
